//
//  KLMAddDeviceController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/27.
//

import UIKit
import nRFMeshProvision

private let cellId = "AddDeviceCell"

enum MainBarType: CaseIterable {
    case mainBarLight
    case mainBarDataRelay
    case mainBarPanel
    case mainBarController
    case mainBarRKScene
    case mainBarRKCustomer
    case mainBarRKHotMap
    case mainBarRKBed
    case mainBarTableLamp
    case mainLineLamp
    
    case newProduction ///新产品试用入口
}
enum NetworkType: Int {
    case wifi = 1
    case networkCable = 2
}

class KLMAddDeviceController: KLMBaseController {
    
    // MARK: - 扫描动画
    private let animationView: KLMAnimationView = {
        let animationView = KLMAnimationView()
        animationView.configure(animationName: "Scan")
        animationView.isLooping = true
        animationView.animationSpeed = 1
        animationView.setContentMode(.scaleAspectFill)
        return animationView
    }()
//    @IBOutlet weak var autoLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    
    ///搜索的蓝牙设备集合
//    private var deviceList: [sectionModel] = []
    private var deviceList: [DiscoveredPeripheral] = []
    ///设备种类集合
    private var deviceTypes: Set<nodeDeviceType> = []
    private var selectedDevices: [DiscoveredPeripheral] = [DiscoveredPeripheral]()
    private var currentNode: Node!
    var semaphore: DispatchSemaphore?
    
    ///是否需要搜索
    private var isNeedSearch: Bool = true
    ///定时器
    let timeCommand = KLMSigMeshCommand()
    var addType: MainBarType!
    var SSID: String?
    var password: String?
    var deviceName = ""
    ///商品条码
    var sku: String?
    var category: Int?
    ///RGB负载类型
    var loadType: Int?
    ///多合一类型
    var allInonesubType: Int?
    /// wifi 1  网线 2
    var networkType: NetworkType?
    let homeRoomId: Int?
    
    init(homeRoomId: Int? = nil) {
        self.homeRoomId = homeRoomId
        super.init(nibName: "KLMAddDeviceController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = rgba(243, 243, 246, 1)
        
        addType = .mainBarLight
        deviceTypes.insert(.lineLamp)
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        let layout = KLMCustomFlowLayout()
        layout.cellCountPerRow = 1
        layout.itemSize = CGSizeMake(200, 94)
        collectionView.collectionViewLayout = layout
        
        collectionView.register(UINib(nibName: "KLMDeviceListCell", bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView.delegate = self
        collectionView.dataSource = self
        
        
        collectionView.backgroundColor = .clear
        
//        autoLabel.configStyle(with: "自动扫描", font: UIFont(safeName: "PingFangSC-Regular", size: 14), titleColor: rgba(38, 38, 38, 0.90))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        KLMMessageManager.sharedInstacnce.delegate = self
        searchDevice()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        KLMSigScanManager.shared.stopScanning()
        if navigationController?.viewControllers.firstIndex(of: self) == nil{
            KLMSigConnectManager.shared.stopConnectAllDevices()
        }
    }
    // MARK: - 1、搜索设备，限制显示的设备类型
    func searchDevice() {
        if isNeedSearch == false {
            return
        }
        hideEmptyState()
        playAnimationView()
        
        deviceList.removeAll()
        collectionView.reloadData()
        selectedDevices.removeAll()
        
        KLMSigScanManager.shared.startScan { [weak self] device in
            guard let self = self else { return }
            
            print(device.device.name ?? "", device.peripheral.name ?? "", device.Rssi, device.deviceType)
            
            for (index, model) in deviceList.enumerated() {
                if device.peripheral.identifier == model.peripheral.identifier {
                    deviceList[index].Rssi = device.Rssi
                    if let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? KLMDeviceListCell {
                        cell.updateRssi(device.Rssi)
                    }
//                    collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
                }
            }
                        
            switch addType {
            case .mainBarLight:
                if KLMSmartNode.isTracklight(deviceType: device.deviceType) {
                    deviceTypes.insert(device.deviceType)
                }
            case .mainBarDataRelay:
                deviceTypes = [.gateway,
                              .gatewayNew]
            case .mainBarPanel:
                deviceTypes = [.scene1,
                              .scene2,
                              .scene3,
                              .singleFire1,
                              .singleFire2,
                              .singleFire3]
            case .mainBarController:
                deviceTypes = [.qieXiang,
                              .RGBControl,
                              .danse,
                              .shuangse,
                              .WWCW,
                              .Dali]
            case .mainBarRKScene:
                deviceTypes = [.embeddedSceneController,
                              .RKAllInOne]
            case .mainBarRKCustomer:
                deviceTypes = [.RKAllInOne]
            case .mainBarRKHotMap:
                deviceTypes = [.RKAllInOne]
            case .mainBarRKBed:
                deviceTypes = [.RKAllInOne]
            case .mainBarTableLamp:
                deviceTypes = [.tableLamp]
            case .mainLineLamp:
                deviceTypes = [.lineLamp]
            case .newProduction:
                deviceTypes = [.Accelerometer,
                              .Illuminometer]
            default:
                break
            }
            
            print("设备类型：", deviceTypes)
            if deviceTypes.contains(device.deviceType) {
                if deviceList.isEmpty {
                    deviceList.append(device)
                    collectionView.performBatchUpdates ({ [weak self] in
                        guard let self = self else { return }
                        self.collectionView.insertItems(at: [IndexPath(item: 0, section: 0)])
                    }, completion: nil)
                } else {
                    if !deviceList.map({$0.peripheral.identifier}).contains(device.peripheral.identifier) {
                        deviceList.append(device)
                        collectionView.performBatchUpdates({ [weak self] in
                            guard let self = self else { return }
                            self.collectionView.insertItems(at: [IndexPath(item: self.deviceList.count-1, section: 0)])
                        }, completion: nil)
                    }
                }
                print("设备数量：", deviceList.count)
                foundDevice()
            }
            
        } commandResult: { [weak self] isSuccess, error in
            guard let self = self else { return }
            if isSuccess == false {
                noFoundDevice()
            }
        }
    }
    func foundDevice() {
        
        hideAnimationView()
        KLMSigScanManager.shared.stopScanTimer()
//        self.tableView.mj_header?.endRefreshing()
    }
    func noFoundDevice() {
        hideAnimationView()
        showEmptyView()
        KLMLog("没有发现设备")
    }
    
    override func setNavBarStyle() {
        customNavBarAppearance(barTintColor: rgba(243, 243, 246, 1), titleColor: nil)
    }
    
    override func tapEmptyButton(_ button: UIButton) {
        searchDevice()
    }
    // MARK: - 3、添加设备
    @objc private func add() {
        
        if selectedDevices.isEmpty {
            return
        }
        if selectedDevices.count == 1 {
            let model = selectedDevices[0]
            var index = 0 // 0无     1WiFi+网线    2WiFi   3网线
            if model.deviceType == .RKAllInOne { ///空间智能（客流和热力图）必须用网线
                if addType == .mainBarRKCustomer || addType == .mainBarRKHotMap {
                    index = 3
                } else {
                    index = 1
                }
            }
            if model.deviceType == .tableLamp || model.deviceType == .lineLamp {
                index = 2
            }
            if model.deviceType == .embeddedSceneController {
                index = 1
            }
            if model.deviceType == .gatewayNew {
                index = 3
            }
            if index == 1 {
                let vc = UIAlertController.init(title: KLMLocalizable.LANGLOC("Network Connection"), message: KLMLocalizable.LANGLOC("Select Wi-Fi or Cable"), preferredStyle: .alert)
                vc.addAction(UIAlertAction.init(title: KLMLocalizable.LANGLOC("Wi-Fi"), style: .default, handler: { action in
                    self.networkType = .wifi
                    let vc = KLMGatewayWiFiController()
                    self.isNeedSearch = false
                    vc.wifiBlock = { [weak self] name, password in
                        guard let self = self else { return }
                        self.SSID = name
                        self.password = password
                        DispatchQueue.main.asyncAfter(deadline: 0.5) {
                            self.isNeedSearch = true
                            self.connectDevice(model: model)
                        }
                    }
                    DispatchQueue.main.asyncAfter(deadline: 0.5) {
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }))
                vc.addAction(UIAlertAction.init(title: KLMLocalizable.LANGLOC("Cable"), style: .default, handler: { action in
                    self.networkType = .networkCable
                    self.connectDevice(model: model)
                }))
                self.present(vc, animated: true)
                return
            }
            /// 雅典娜线条灯
            if index == 2 {
                /// 配置Wi-Fi控制器
                let vc = KLMGatewayWiFiController()
                self.isNeedSearch = false
                /// 配置Wi-Fi完成回调
                vc.wifiBlock = { [weak self] name, password in
                    guard let self = self else { return }
                    self.SSID = name
                    self.password = password
                    DispatchQueue.main.asyncAfter(deadline: 0.5) {
                        self.isNeedSearch = true
                        self.networkType = .wifi
                        self.connectDevice(model: model)
                    }
                }
                DispatchQueue.main.asyncAfter(deadline: 0.5) {
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                return
            }
            if index == 3 {
                KLMAlertController.showAlertWithTitle(title: KLMLocalizable.LANGLOC("Please make sure network cable is connected"), message: nil, sure: {
                    self.networkType = .networkCable
                    self.connectDevice(model: model)
                })
                return
            }
            connectDevice(model: model)
            return
        }
        connectAndActiveDevice()
    }
    // MARK: - 4、设备连接Wi-Fi后，连接设备
    func connectDevice(model: DiscoveredPeripheral) {
        
        SVProgressHUD.show(withStatus: "Connecting...")
        SVProgressHUD.setDefaultMaskType(.black)
        KLMLog("---------------\(model.device.uuid)")
        KLMSigConnectManager.shared.startConnect(discoveredPeripheral: model) { [weak self] isSuccess, error in
            SVProgressHUD.dismiss()
            guard let self = self else { return }
            if isSuccess {
                if model.deviceType == .RGBControl { ///RGB 控制器
                    let vc = KLMDeviceNameControllerPopViewController()
                    vc.modalPresentationStyle = .overCurrentContext
                    vc.modalTransitionStyle = .crossDissolve
                    vc.devicesubType = model.deviceType == .RGBControl ? .RGBSubType : .allInOneType
                    
                    //名称
                    if model.deviceType == .RGBControl {
                        let name = KLMTool.getDeviceName(name: model.device.name)
                        vc.name = name
                    }
                    
                    vc.nameBlock = { [weak self] name in
                        
                        guard let self = self else { return }
                        self.deviceName = name
                        
                        //开始配网
                        self.activeDevice(model: model)
                    }
                    vc.typeBlock = { [weak self] type in
                        
                        guard let self = self else { return }
                        if model.deviceType == .RGBControl {
                            self.loadType = type
                        }
                    }
                    
                    vc.cancelBlock = {
                        
                        ///断开连接
//                        KLMSigConnectManager.shared.stopConnectAllDevices()
                    }
                    present(vc, animated: true, completion: nil)
                    return
                }
                let vc = KLMDeviceNameAndTypePopViewController()
                vc.modalPresentationStyle = .overCurrentContext
                vc.modalTransitionStyle = .crossDissolve
                vc.deviceType = model.deviceType
                ///双摄才有sku
                if KLMSmartNode.haveTwoCamera(deviceType: model.deviceType) {
                    vc.isHideSkuView = false
                }
                ///有摄像头才有使用场合
                if KLMSmartNode.haveCamera(deviceType: model.deviceType) {
                    if KLMSmartNode.isFresh(deviceType: model.deviceType) {
                        vc.isFresh = true
                    }
                    if KLMSmartNode.isMetaUni(deviceType: model.deviceType)  == false { ///双色温没有使用场合
                        vc.isHideUseOccasionBgView = false
                    }
                }
                
                ///填充广播的使用场合
                let useOccation: UInt8 = model.device.uuid.uuid.8
                if useOccation > 0 {
                    vc.useOccation = Int(useOccation)
                }
                
                //名称
                let name = KLMTool.getDeviceName(name: model.device.name)
                vc.name = name
                
                ///多合一传感器子类
                if model.deviceType == .RKAllInOne {
                    switch addType {
                    case .mainBarRKScene:
                        allInonesubType = 1
                    case .mainBarRKCustomer:
                        allInonesubType = 2
                    case .mainBarRKHotMap:
                        allInonesubType = 4
                    case .mainBarRKBed:
                        allInonesubType = 3
                    default:
                        break
                    }
                }
                
                vc.nameBlock = { [weak self] name in
                    
                    guard let self = self else { return }
                    self.deviceName = name
                    //开始配网
                    self.activeDevice(model: model)
                }
                vc.typeBlock = { [weak self] type in
                    
                    guard let self = self else { return }
                    self.category = type
                }
                
                vc.skuBlock = { [weak self] sku in
                    guard let self = self else { return }
                    self.sku = sku
                    
                }
                vc.cancelBlock = {
                    
                    ///断开连接
//                    KLMSigConnectManager.shared.stopConnectAllDevices()
                }
                present(vc, animated: true, completion: nil)
            } else {
                KLMShowError(error)
            }
        }
    }
    ///批量添加
    private func connectAndActiveDevice() {
//        
//        SVProgressHUD.show(withStatus: "Connecting...")
//        SVProgressHUD.setDefaultMaskType(.black)
//        KLMSigConnectAndActiveManager.shared.startConnectAndActive(devices: selectedDevices) { [weak self] node in
//            guard let self = self else { return }
//            KLMLog("配网成功")
//            
////            for (row, MM) in deviceLists.enumerated() {
////                if MM.device.uuid == node.uuid {
////                    if let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) as? KLMDeviceAddTestCell {
////                        cell.setStatus = 1
////                    }
////
////                }
////            }
//            
//                
//            for (section, model) in deviceList.enumerated() {
//                for (row, MM) in model.list.enumerated() {
//                    if MM.device.uuid == node.uuid {
//                        if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as? KLMDeviceAddTestCell {
//                            cell.setStatus = 1
//                        }
//                        
//                    }
//                }
//            }
//                ///注册设备到服务器上
//                KLMService.addDevice(deviceName: node.nodeName , deviceType: node.deviceType.rawValue, uuid: node.nodeuuidString, unicastAddress: node.unicastAddress, node: node) { response in
//                    ///设备在线
//                    KLMMesh.instacnce.onLineNodes.insert(node.nodeuuidString)
//                    ///设备添加进分组
//                    self.currentNode = node
//                    self.semaphore = Dispatch.DispatchSemaphore(value: 0)
//                    if self.addType == .mainBarLight {
//                        if let group = KLMMesh.loadGroup(), group.address != AllGroupAddress,
//                           group.address != unGroupAddress {
//                            KLMMessageManager.sharedInstacnce.addNodeToGroup(withNode: node, withGroup: group.group!)
//                        } else {
//                            self.semaphore?.signal()
//                        }
//                    } else {
//                        self.semaphore?.signal()
//                    }
//                } failure: { error in
//                    KLMLog("注册到服务器失败")
//                    self.resetNode(node: node)
//                }
//            
//            
//        } activeFailure: { [weak self] device, error in
//            guard let self = self else { return }
//            KLMLog("配网失败了")
//            
////            for (row, MM) in deviceLists.enumerated() {
////                if MM.device.uuid == device.device.uuid {
////                    if let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) as? KLMDeviceAddTestCell {
////                        cell.setStatus = 2
////                    }
////
////                }
////            }
//            
//            for (section, model) in deviceList.enumerated() {
//                for (row, MM) in model.list.enumerated() {
//                    if MM.device.uuid == device.device.uuid {
//                        if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as? KLMDeviceAddTestCell {
//                            cell.setStatus = 2
//                        }
//                        
//                    }
//                }
//            }
//            
//            KLMShowError(error)
//            ///失败复位设备
//            if let network = MeshNetworkManager.instance.meshNetwork {
//                if let node = network.node(for: device.device) {
//                    resetNode(node: node)
//                }
//            }
//        } didConnectDevice: { [weak self] device in
//            guard let self = self else { return }
//            
////            for (row, MM) in deviceLists.enumerated() {
////                if MM.device.uuid == device.device.uuid {
////                    if let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) as? KLMDeviceAddTestCell {
////                        cell.startActivity()
////                    }
////
////                }
////            }
//            
//            for (section, model) in deviceList.enumerated() {
//                for (row, MM) in model.list.enumerated() {
//                    if MM.device.uuid == device.device.uuid {
//                        if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as? KLMDeviceAddTestCell {
//                            cell.startActivity()
//                        }
//                        
//                    }
//                }
//            }
//            
//        } allFinish: { [weak self] isAll in
//            guard let self = self else { return }
//            KLMLog("设备已经完成配网，不管是成功或者失败")
//            SVProgressHUD.dismiss()
//            //刷新首页,控制器和网关选择未分组
//            DispatchQueue.global().async {
//                self.semaphore?.wait(timeout: 10)
//                DispatchQueue.main.async {
//                    if self.addType != .mainBarLight {
//                        KLMMesh.removeGroup()
//                    }
//                    
//                    DispatchQueue.main.asyncAfter(deadline: 2) { ///延迟一点刷新首页，让设备添加到服务器完成之后才刷新
//                        SVProgressHUD.dismiss()
//                        NotificationCenter.default.post(name: .deviceAddSuccess, object: nil)
//                        self.navigationController?.popViewController(animated: true)
//                    }
//                }
//            }
//        }
    }
    // MARK: - 5、配网
    func activeDevice(model: DiscoveredPeripheral) {
        
        let bearer = KLMSigConnectManager.shared.gattBearers.first(where: {$0.identifier == model.peripheral.identifier})
        /// 配网操作
        KLMSigActiveManager.shared.startActive(discoveredPeripheral: model, gattBearer: bearer!) {[weak self] node in
            guard let self = self else { return }
            
            //正式APP
            node.name = self.deviceName
            ///灯带控制器
            node.loadType = self.loadType
            ///多合一传感器
            node.allInOneType = self.allInonesubType
            
            //记录当前设备
            KLMHomeManager.sharedInstacnce.smartNode = node
            
            //网关发送WiFi信息
            if node.deviceType == .gateway {
//                self.sendGatewayWifi()
                return
            }
            //RK发送WiFi信息
            if node.isRK {
                print("RK发送WiFi信息...")
                self.sendRKWifiMessage()
                return
            }
            
            print("activeDevice，注册设备到服务器上")
            ///注册设备到服务器上（家或者房间添加设备）
            KLMRequest.homeCreateDevice(homeRoomId: homeRoomId, deviceName: self.deviceName , deviceType: node.deviceType.rawValue, uuid: node.nodeuuidString, unicastAddress: node.unicastAddress, node: node, commoditySku: self.sku) { response in
                
                KLMHomeMesh.instacnce.onLineNodes.insert(node.nodeuuidString)
                //连接成功
                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Connection successful"))
                
                //刷新首页
                NotificationCenter.default.post(name: .deviceAddSuccess, object: nil)
                
                //发送分类指令
                if let cc = self.category {
                    let parame = parameModel(dp: .category, value: cc.decimalTo2Hexadecimal())
                    KLMSmartNode.sharedInstacnce.sendMessage(parame, toNode: KLMHomeManager.currentNode, isCanInternet: false)
                }
                
                self.navigationController?.popViewController(animated: true)
                
                ///创建信号量，需要分组，需分组完成后才能执行下面步骤，不然进入设置页面，分组完成代理在当前页面无法执行
//                self.semaphore = Dispatch.DispatchSemaphore(value: 0)
//                if self.addType != .mainBarLight {
//                    KLMMesh.removeGroup()
//                    self.semaphore?.signal()
//                } else {
//                    ///设备添加进分组
//                    self.currentNode = node
//                    if let group = KLMMesh.loadGroup(), group.address != AllGroupAddress,
//                       group.address != unGroupAddress {
//                        KLMMessageManager.sharedInstacnce.addNodeToGroup(withNode: node, withGroup: group.group!)
//                    } else {
//                        self.semaphore?.signal()
//                    }
//                }
//                
//                DispatchQueue.global().async {
//                    self.semaphore?.wait(timeout: 10)
//                    ///主线程刷新
//                    DispatchQueue.main.async {
                        
                        
//                        if apptype == .test {
//                            let vc = KLMTestSectionTableViewController()
//                            self.pushVc(Vc: vc)
//                            return
//                        }
//                        
//                        if node.isController {
//                            
//                            let vc = KLMControllerSettingViewController()
//                            self.pushVc(Vc: vc)
//                            return
//                        }
//                        
//                        if node.isPanel {
//                            let vc = KLMPanelDeviceSettingViewController()
//                            self.pushVc(Vc: vc)
//                            return
//                        }
//                        
//                        if node.deviceType == .Accelerometer {
//                            let vc = KLMAccDeviceSettingViewController()
//                            self.pushVc(Vc: vc)
//                            return
//                        }
//                        
//                        let vc = KLMDeviceEditViewController()
//                        vc.isFromAddDevice = true
//                        self.pushVc(Vc: vc)
//                    }
//                }
            } failure: { error in
                KLMLog("注册到服务器失败")
                KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + error.localizedDescription + "(1)", sure: {
                    self.navigationController?.popViewController(animated: true)
                })
                self.resetNode(node: node)
            }
            
        } activeFailure: {[weak self] device, error in
            guard let self = self else { return }
            ///配网失败
            KLMShowError(error)
            ///失败重置设备
            if let network = MeshNetworkManager.instance.meshNetwork {
                if let node = network.node(for: device.device) {
                    KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + (error.message ?? "") + "(2)", sure: {
                        self.navigationController?.popViewController(animated: true)
                    })
                    resetNode(node: node)
                }
            }
        }
    }
    // MARK: - 6、发送Wi-Fi信息配网
    private func sendRKWifiMessage() {
        
        KLMLog("sendRKWifiMessage...")
        
        KLMSmartNode.sharedInstacnce.delegate = self
        
        SVProgressHUD.show(withStatus: KLMLocalizable.LANGLOC("Get device info"))
        
        let urlSSID: String = SSID ?? ""
        let urlPassword: String = password ?? ""
        
        //32
        var urlSSIDBytes: [UInt8] = [UInt8](urlSSID.data(using: .utf8)!)
        urlSSIDBytes = urlSSIDBytes + [UInt8].init(repeating: 0, count: 32 - urlSSIDBytes.count)
        //32
        var urlPasswordBytes: [UInt8] = [UInt8](urlPassword.data(using: .utf8)!)
        urlPasswordBytes = urlPasswordBytes + [UInt8].init(repeating: 0, count: 32 - urlPasswordBytes.count)
        //阿里云或者亚马逊 -- 1
        var type: [UInt8] = [UInt8(1)]
        if serverType == .Alibaba {
            type = [UInt8(2)]
        }
        /// tenantCode -- 16
        var appType = [UInt8](tenantCode.data(using: .utf8)!)
        appType = appType + [UInt8].init(repeating: 0, count: 16 - appType.count)
        
        var totalBytes = urlSSIDBytes + urlPasswordBytes + type + appType
        if let allInonesubType = allInonesubType {
            totalBytes = totalBytes + [UInt8(allInonesubType)]
        }
        ///是嵌入式场景控制器拼接一个1 跟空间智能保持一致
        if KLMHomeManager.sharedInstacnce.smartNode?.deviceType == .embeddedSceneController {
            totalBytes = totalBytes + [UInt8(1)]
        }
        if let networkType = networkType {
            totalBytes = totalBytes + [UInt8(networkType.rawValue)]
        }
        let parameters = Data.init(bytes: totalBytes, count: totalBytes.count)
        let allBytes: String = parameters.hex
        let parame = parameModel(dp: .RKWifiMessage, value: allBytes)
        KLMSmartNode.sharedInstacnce.sendMessage(parame, toNode: KLMHomeManager.currentNode, isCanInternet: false)
    }
    // MARK: - 重置节点
    private func resetNode(node: Node) {
        print("resetNode", node.name ?? node.nodeuuidString)
        KLMSmartNode.sharedInstacnce.delegate = self
        KLMSmartNode.sharedInstacnce.resetNode(node: node)
    }
    private func pushVc(Vc: UIViewController) {
        self.navigationController?.pushViewController(Vc, animated: true)
        if var nvcs = Vc.navigationController?.viewControllers {
            //移除当前导航控制器
            nvcs.remove(self)
            Vc.navigationController?.viewControllers = nvcs
        }
    }
    // MARK: - 隐藏/显示提示view
    func playAnimationView() {
        view.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.width.height.equalTo(220)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-KLM_NavBarHeight)
        }
        animationView.play()
    }
    func hideAnimationView() {
        animationView.hide()
    }
    func showEmptyView() {
        self.showEmptyState(title: KLMLocalizable.LANGLOC("No devices found"), buttonTitle: KLMLocalizable.LANGLOC("Search again"))
    }
    override func showEmptyButton() -> Bool {
        true
    }
    deinit {
        KLMSigScanManager.shared.stopScanning()
    }
}

extension KLMAddDeviceController: KLMMessageManagerDelegate {
    
    func messageManager(_ manager: KLMMessageManager, didHandleGroup unicastAddress: Address, error: MessageError?) {
        self.semaphore?.signal()
//        if error == nil { ///成功
//            KLMService.addDeviceToGroup(groupId: Int(KLMMesh.loadGroup()!.group!.address.address), uuid: self.currentNode.nodeuuidString) { response in
//
//            } failure: { error in }
//        }
    }
}

extension KLMAddDeviceController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return deviceList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! KLMDeviceListCell
        cell.scanDeviceInfo = deviceList[indexPath.item]
        return cell
    }
}

extension KLMAddDeviceController: UICollectionViewDelegateFlowLayout {

    // MARK: - 2、点击连接设备
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = deviceList[indexPath.row]
        
        if let index = selectedDevices.firstIndex(where: { $0.peripheral == model.peripheral }) { ///取消选择
            KLMSigConnectManager.shared.stopConnectDevcie(device: model)
            selectedDevices.remove(at: index)
            collectionView.reloadData()
        } else { ///选择
            ///mesh限定的最大数量
            if KLMSmartGroup.allNodes().count + selectedDevices.count >= 280 {
                SVProgressHUD.showInfo(withStatus: String.init(format: KLMLocalizable.LANGLOC("Select at most %d lights"), KLMSmartGroup.allNodes().count))
                return
            }
            ///最多添加设备
            if selectedDevices.count >= 7 {
                SVProgressHUD.showInfo(withStatus: String.init(format: KLMLocalizable.LANGLOC("Select at most %d lights"), selectedDevices.count))
                return
            }
            
            SVProgressHUD.show()
            KLMSigConnectManager.shared.startConnect(discoveredPeripheral: model) {[weak self] isSuccess, error in
                SVProgressHUD.dismiss()
                guard let self = self else { return }
                if isSuccess {
                    selectedDevices.append(model)
                    collectionView.reloadData()
                    // 添加
                    add()
                } else {
                    KLMShowError(error)
                }
            }
        }
    }
}
// MARK: - KLMSmartNodeDelegate代理
extension KLMAddDeviceController: KLMSmartNodeDelegate {
    
    func smartNode(_ manager: KLMSmartNode, didReceiveVendorMessage message: responsParame?) {
        
        if message?.dp == .DataRelay, message?.opCode == .send {
            
            ///注册设备到服务器上（家或者房间添加设备）
            KLMRequest.homeCreateDevice(homeRoomId: homeRoomId, deviceName: KLMHomeManager.currentNode.nodeName, deviceType: KLMHomeManager.currentNode.deviceType.rawValue, uuid: KLMHomeManager.currentNode.nodeuuidString, unicastAddress: KLMHomeManager.currentNode.unicastAddress, node: KLMHomeManager.currentNode) { response in
                
                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                ///刷新首页
                NotificationCenter.default.post(name: .deviceAddSuccess, object: nil)
                DispatchQueue.main.asyncAfter(deadline: 0.5) {
//                    let vc = KLMGatewaySettingViewController()
//                    self.pushVc(Vc: vc)
                }
                
            } failure: { error in
                KLMLog("注册到服务器失败")
                KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + error.localizedDescription + "(3)", sure: {
                    self.navigationController?.popViewController(animated: true)
                })
                self.resetNode(node: KLMHomeManager.currentNode)
            }
            
        }
        
        if message?.dp == .RKWifiMessage, message?.opCode == .send {
            if let value: Data = message?.value as? Data {
                if value.count == 1 {///设备接收到WIFi信息，然后回复
                    SVProgressHUD.show(withStatus: KLMLocalizable.LANGLOC("Connect to a network"))
                    ///启动定时,等待设备连网
                    timeCommand.timeout = 30
                    timeCommand.startTimer { [weak self] error in
                        guard let self = self else { return }
                        KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + KLMLocalizable.LANGLOC("Please check the network cable or Wi-Fi connection.") + "(6)", sure: {
                            self.navigationController?.popViewController(animated: true)
                        })
                        ///复位
                        self.resetNode(node: KLMHomeManager.currentNode)
                    }
                    return
                }
                ///停止定时
                timeCommand.commandResponseFinishWithCommand()
                SVProgressHUD.show(withStatus: KLMLocalizable.LANGLOC("Receive device info"))
                let str = String.init(data: value, encoding: .utf8)
                KLMLog("RKWifiRecevice = \(String(describing: str))")
                let rkModel = try? JSONDecoder().decode(RKModel.self, from: value)
                if rkModel?.code == 200 {
                    ///存储WiFi信息
                    KLMHomeManager.cacheWIFIMsg(SSID: SSID, password: password)
                    let model = KLMWiFiModel.init(WiFiName: SSID, WiFiPass: password)
                    KLMWiFiManager.saveWiFiName(wifiModel: model)
                    if KLMTool.isEmptyString(string: rkModel?.data?.DeviceName) == nil || KLMTool.isEmptyString(string: rkModel?.data?.ProductKey) == nil {
                        KLMAlertController.showAlertWithTitle(title: nil, message: "deviceKey or productKey is null")
                    }
                    ///注册设备到服务器上
                    var subType = ""
                    if let allInonesubType = allInonesubType {
                        subType = "\(allInonesubType)"
                    }
                    ///注册设备到服务器上（家或者房间添加设备）
                    KLMRequest.homeCreateDevice(homeRoomId: homeRoomId, deviceName: KLMHomeManager.currentNode.nodeName , deviceType: KLMHomeManager.currentNode.deviceType.rawValue + subType, uuid: KLMHomeManager.currentNode.nodeuuidString, unicastAddress: KLMHomeManager.currentNode.unicastAddress, node: KLMHomeManager.currentNode, wifiStatus: 1, deviceKey: rkModel?.data?.DeviceName, productKey: rkModel?.data?.ProductKey) { response in
                        
                        SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                        ///刷新首页
                        var object: MainBarType?
                        if KLMHomeManager.currentNode.deviceType == .RKAllInOne {
                            switch KLMHomeManager.currentNode.rkAllInOneType {
                            case .sceneRecognition:
                                object = .mainBarRKScene
                            case .furnitureStore:
                                object = .mainBarRKBed
                            case .CustomerCounting:
                                object = .mainBarRKCustomer
                            case .Heatmap:
                                object = .mainBarRKHotMap
                            default:
                                break
                            }
                        }
                        NotificationCenter.default.post(name: .deviceAddSuccess, object: object)
                        DispatchQueue.main.asyncAfter(deadline: 1) {
//                            if apptype == .test {
//                                let vc = KLMTestSectionTableViewController()
//                                self.pushVc(Vc: vc)
//                                return
//                            }
//                            let vc = KLMRKSettingViewController()
//                            self.pushVc(Vc: vc)
                            self.navigationController?.popViewController(animated: true)
                        }
                        
                    } failure: { error in
                        SVProgressHUD.dismiss()
                        KLMLog("注册到服务器失败")
                        KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + error.localizedDescription + "(4)", sure: {
                            self.navigationController?.popViewController(animated: true)
                        })
                        self.resetNode(node: KLMHomeManager.currentNode)
                    }
                    
                } else {
                    SVProgressHUD.dismiss()
                    var message = KLMLocalizable.LANGLOC("Please check the network cable or Wi-Fi connection.")
                    if rkModel?.code == 401 {
                        message = KLMLocalizable.LANGLOC("Please make sure network cable is connected")
                    }
                    KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + "\(String(describing: rkModel?.code))" + "(5)" + message, sure: {
                        self.navigationController?.popViewController(animated: true)
                    })
                    ///复位
                    self.resetNode(node: KLMHomeManager.currentNode)
                }
            }
        }
    }
    
    func smartNodeDidResetNode(_ manager: KLMSmartNode) {
        SVProgressHUD.dismiss()
        print("smartNodeDidResetNode...")
        NotificationCenter.default.post(name: .deviceReset, object: nil)
    }
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?) {
        KLMShowError(error)
        ///RK设备配网超时，重置设备
        if error?.code == timeOutCode && error?.dp == .RKWifiMessage {
            KLMAlertController.showAlertWithTitle(title: nil, message: "Timed out." + KLMLocalizable.LANGLOC("Failed to add device.Please try again.") + KLMLocalizable.LANGLOC("Please check the network cable or Wi-Fi connection."), sure: {
                self.navigationController?.popViewController(animated: true)
            })
            ///复位
            resetNode(node: KLMHomeManager.currentNode)
        }
    }
}
